package cn.zhoujing.demo.redis.service.factory;

import cn.zhoujing.demo.redis.common.dto.LoginDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;

import java.util.HashMap;
import java.util.Map;

/**
 * 授予模式-授权码
 *
 * @author zhoujing
 * @createTime 2023/12/3 - 2:14
 */
@Component(value = "authorization_code")
public class GrantCodeFactoryImpl implements GrantTypeFactory {


    @Qualifier(value = "tokenEndpoint")
    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Override
    public OAuth2AccessToken getAccountToken(LoginDTO dto, UsernamePasswordAuthenticationToken token) throws HttpRequestMethodNotSupportedException {
        Map<String, String> params = new HashMap<>();
        params.put("code", dto.getCode());
        params.put("redirect_uri", dto.getRedirectUri());
        params.put("grant_type", dto.getGrantType());
        OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(token, params).getBody();
        return accessToken;
    }
}
